package cc.magicjson.example.demo.spring.bean;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class CustomSingletonBeanRegistry {

    private Map<String, Object> singletonObjects;

    public CustomSingletonBeanRegistry(int initialCapacity) {
        this.singletonObjects = new ConcurrentHashMap<>(initialCapacity);
    }

    public synchronized void addSingleton(String beanName, Object singletonObject) {
        if (singletonObjects.size() >= singletonObjects.size() * 0.75) {
            expandCapacity();
        }
        singletonObjects.put(beanName, singletonObject);
    }

    public Object getSingleton(String beanName) {
        return singletonObjects.get(beanName);
    }

    private void expandCapacity() {
        int newCapacity = singletonObjects.size() * 2;
        Map<String, Object> newMap = new ConcurrentHashMap<>(newCapacity);
        newMap.putAll(singletonObjects);
        singletonObjects = newMap;
    }

    public static void main(String[] args) {
        int estimatedBeanCount = 1000;
        int initialCapacity = (int) (estimatedBeanCount / 0.75);

        CustomSingletonBeanRegistry registry = new CustomSingletonBeanRegistry(initialCapacity);

        // 示例：添加单例对象并监控扩容
        for (int i = 0; i < 1200; i++) {
            registry.addSingleton("bean" + i, new Object());
        }

        System.out.println("Current capacity: " + registry.singletonObjects.size());
    }
}
